﻿package component.fileupload.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpDownloadUtil {

	public static boolean checkDirectory(String tragetFile) {
		File targetFile = new File(tragetFile);
		File directory = new File(targetFile.getParent());
		if (!directory.exists() && !directory.mkdirs()) {
			return false;
		}
		return true;
	}

	public static boolean downloadFile(String httpFile, String saveFileName) {
		if (httpFile == null || saveFileName == null) {
			return false;
		}
		URL url = null;
		try {
			url = new URL(httpFile);
		} catch (MalformedURLException urlex) {
			urlex.printStackTrace();
			return false;
		}
		
		if (!checkDirectory(saveFileName)) {
			return false;
		}

		try {
			DataInputStream in = new DataInputStream(new BufferedInputStream(
					url.openStream()));
			DataOutputStream out = new DataOutputStream(
					new BufferedOutputStream(new FileOutputStream(saveFileName)));
			byte[] buf = new byte[1024];
			int readed = 0;
			while ((readed = in.read(buf)) != -1) {
				out.write(buf, 0, readed);
			}
			out.close();
			in.close();
		} catch (IOException ex) {
			ex.printStackTrace();
			return false;
		}
		return true;
	}
}
